package com.example.okhttp;

import android.Manifest;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import io.reactivex.functions.Consumer;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class MainActivity extends AppCompatActivity {

    private OkHttpClient client = new OkHttpClient();
    //        private String url = "http://api.tianapi.com/social/?key=861a794733dd2b057e415d822bef9586&num=10";
    private String url = "http://192.168.0.4:8080/Okhttp/";
    //    private String url = "https://www.imooc.com/";
    private TextView result;
    private ImageView imageview;
    private String TAG = MainActivity.class.getSimpleName();
    private static final int MSG_FAILE = 101;
    private static final int MSG_SUCCESS = 102;
    private static final int MSG_SUCCESS_DOWNLOAD = 103;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_FAILE:
                    Log.i(TAG, "handleMessage: " + msg.obj);
                    break;
                case MSG_SUCCESS:
                    Log.i(TAG, "handleMessage: " + msg.obj);
                    String newsStr = (String) msg.obj;
                    result.append(newsStr);
                    break;
                case MSG_SUCCESS_DOWNLOAD:
                    int sum = 0;
                    ResponseBody body = (ResponseBody) msg.obj;
                    InputStream is = body.byteStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(is);
                    imageview.setImageBitmap(bitmap);
                    Log.i(TAG, "handleMessage: " + bitmap.getWidth() + "length" + body.contentLength());
                    int len = 0;
                    byte[] buff = new byte[128];
                    File file = new File(Environment.getExternalStorageDirectory() + "/1111.png");
                    try {
                        FileOutputStream fos = new FileOutputStream(file);
                        while ((len = is.read(buff)) != -1) {
                            fos.write(buff, 0, len);
                            sum += len;
                            result.append(body.contentLength() + "----->" + sum + "\n");
                            Log.i(TAG, "handleMessage: " + body.contentLength() + "----->" + sum);
                        }

                        fos.close();
                        fos.flush();
                        is.close();

                        Log.i(TAG, "handleMessage: " + "MSG_SUCCESS_DOWNLOAD1");

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE).subscribe(new Consumer<Permission>() {
            @Override
            public void accept(Permission permission) throws Exception {

            }
        });

//        http://api.tianapi.com/social/?key=861a794733dd2b057e415d822bef9586&num=10
        result = findViewById(R.id.tv_result);
        imageview = findViewById(R.id.iv_result);
    }

    public void doGet(View view) {

        final Request request = new Request.Builder()
                .get()
                .url(url + "login?name=luocj&password=123456")
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                Message message = new Message();
                message.what = MSG_FAILE;
                message.obj = e.toString();
                mHandler.sendMessageDelayed(message, 1000);
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                Message message = new Message();
                message.what = MSG_SUCCESS;
                message.obj = response.body().string();
                mHandler.sendMessageDelayed(message, 1000);
            }
        });

    }

    public void doPost(View view) {
        FormBody.Builder form = new FormBody.Builder();
        FormBody build = form.add("name", "luocj111")
                .add("password", "12123123")
                .build();

        Request.Builder builder = new Request.Builder();
        Request request = builder
                .url(url + "login")
                .post(build)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                Message message = new Message();
                message.what = MSG_FAILE;
                message.obj = e.toString();
                mHandler.sendMessageDelayed(message, 1000);
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                Message message = new Message();
                message.what = MSG_SUCCESS;
                message.obj = response.body().string();
                mHandler.sendMessageDelayed(message, 1000);
            }
        });
    }

    public void doFile(View view) {
        File file = new File(Environment.getExternalStorageDirectory() + "/bg_download.png");
        if (!file.exists()) {
            return;
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        Request request = new Request.Builder()
                .url(url + "postFile")
                .post(requestBody)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                Message message = new Message();
                message.what = MSG_FAILE;
                message.obj = e.toString();
                mHandler.sendMessageDelayed(message, 1000);
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                Message message = new Message();
                message.what = MSG_SUCCESS;
                message.obj = response.body().string();
                mHandler.sendMessageDelayed(message, 1000);
            }
        });

    }

    public void doUpload(View view) {
        File file = new File(Environment.getExternalStorageDirectory() + "/bg_download.png");
        if (!file.exists()) {
            return;
        }

        MultipartBody.Builder builder = new MultipartBody.Builder();
        MultipartBody build = builder.setType(MultipartBody.FORM)
                .addFormDataPart("name", "luochenjian")
                .addFormDataPart("password", "123123123")
                .addFormDataPart("mPhoto", "bg.png", RequestBody.create(MediaType.parse("application/octet-stream"), file))
                .build();

        Request request = new Request.Builder()
                .url(url + "uploadInfo")
                .post(build)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                Message message = new Message();
                message.what = MSG_FAILE;
                message.obj = e.toString();
                mHandler.sendMessageDelayed(message, 1000);
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                Message message = new Message();
                message.what = MSG_SUCCESS;
                message.obj = response.body().string();
                mHandler.sendMessageDelayed(message, 1000);
            }
        });

    }

    //下载文件
    public void doDownload(View view) {
        Request request = new Request.Builder()
                .get()
                .url(url + "files/123.png")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                Message message = new Message();
                message.what = MSG_FAILE;
                message.obj = e.toString();
                mHandler.sendMessageDelayed(message, 1000);
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                ResponseBody body = response.body();
                Message message = new Message();
                message.what = MSG_SUCCESS_DOWNLOAD;
                message.obj = body;
                mHandler.sendMessageDelayed(message, 1000);
            }
        });

    }

    public void doGlide(View view) {
        Log.i(TAG, "doGlide: ");
        Glide.with(MainActivity.this)
                .load("http://192.168.0.4:8080/Okhttp/files/bg.png")
                .skipMemoryCache(true)
                .into(imageview);
    }
}
